package com.laoye.controller;

import com.github.pagehelper.PageInfo;
import com.laoye.bean.Admin;
import com.laoye.dto.*;
import com.laoye.service.AdminService;
import com.laoye.service.AliyunOSSService;
import com.laoye.util.JwtUtil;
import com.laoye.util.Page;
import com.laoye.util.Result;
import com.laoye.util.ThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("admin")
@CrossOrigin
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private StringRedisTemplate redis;
    @Autowired
    private AliyunOSSService aliyunOSSService;

    @GetMapping("info")
    public Result<Admin> getAdmin() {
        return Result.success(adminService.getAdminById());
    }

    /**
     * 用户拉黑
     *
     * @param id 用户id
     * @return 拉黑成功
     */
    @PutMapping("updateUser/{id}")
    public Result<String> updateUser(@PathVariable("id") Integer id) {
        adminService.updateUser(id);
        return Result.success("用户账号取消拉黑成功");
    }
/**
 * 删除用户
 *
 * @param id 用户id
 * @return 删除成功
 */
    @PutMapping("deleteUser/{id}")
    public Result<String> deleteUser(@PathVariable("id") Integer id) {
        adminService.deleteUser(id);
        return Result.success("用户账号拉黑成功");
    }

    /**
     * 获取所有用户信息
     *
     * @param queryType 查询类型
     * @param keyword   关键字
     * @return 返回所有用户信息
     */
    @GetMapping("getAllAdmins")
    public Result<Page<Admin_UserInfo>> getAllAdmins(
            @RequestParam(required = false) String queryType,
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") Integer pageNum,  // 页码，默认第一页
            @RequestParam(defaultValue = "10") Integer pageSize) { // 每页条数，默认10条
        Page<Admin_UserInfo> AdminInfo = adminService.getAllAdmins( queryType, keyword, pageNum, pageSize);
        return Result.success("", AdminInfo);
    }

    /**
     * 获取所有用户信息
     *
     * @param queryType 查询类型
     * @param keyword   关键字
     * @param is_deleted 是否删除
     * @return 返回所有用户信息
     */
    @GetMapping("getUserInfo")
    public Result<PageInfo<Admin_UserInfo>> getUserInfo(
            @RequestParam(required = false) String queryType,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer is_deleted,
            @RequestParam(defaultValue = "1") Integer pageNum,  // 页码，默认第一页
            @RequestParam(defaultValue = "10") Integer pageSize) { // 每页条数，默认10条
        PageInfo<Admin_UserInfo> userInfo = adminService.getAllUserInfo( queryType, keyword, is_deleted, pageNum, pageSize);
        return Result.success("", userInfo);
    }

    /**
     * 修改密码逻辑
     *
     * @param pwdEditDTO 前端传来的修改密码信息
     * @return 返回修改成功
     */
    @PutMapping("updatePassword")
    public Result<String> updatePassword(@RequestBody PwdEditDTO pwdEditDTO) {
        adminService.updatePassword(pwdEditDTO);
        return Result.success("密码修改成功，请重新登录！");
    }

    /**
     * 获取管理员账号
     *
     * @return 返回管理员账号，用于前端修改密码和信息时显示
     */
    @GetMapping("getAdminName")
    public Result<String> updatePassword() {
        String username = adminService.findAdminName(ThreadLocal.getCurrentId());
        return Result.success("", username);
    }

    /**
     * 修改管理员信息
     *
     * @param userEditDTO 管理员信息
     * @return 返回修改成功
     */
    @PutMapping("edit")
    public Result<String> updatePassword(@RequestBody UserEditDTO userEditDTO) {
        adminService.editAdmin(userEditDTO);
        return Result.success("修改成功");
    }


    /**
     * 头像上传
     *
     * @param file 头像文件
     * @return 返回上传成功，并返回上传后的文件路径
     */
    @PostMapping("avatar")
    public Result<String> avatarUpload(@RequestParam("file") MultipartFile file) throws Exception {
        String uploadFile = aliyunOSSService.uploadFile(file);
        adminService.updateAvatar(uploadFile, ThreadLocal.getCurrentId());
        return Result.success("头像上传成功", uploadFile);
    }


    /**
     * 获取当前管理员头像
     *
     * @return 获取当前管理员头像
     */
    @GetMapping("url")
    public Result<String> getAvatarUrl() {
        String avatarUrl = adminService.getAvatarUrl(ThreadLocal.getCurrentId());
        return Result.success("", avatarUrl);
    }



    /**
     * 管理员登录
     *
     * @param loginDTO 登录信息
     * @return 登录成功，并返回token
     */
    @PostMapping("login")
    public Result<String> login(@RequestBody LoginDTO loginDTO) {
        Admin admin = adminService.login(loginDTO);
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", admin.getUsername());
        claims.put("id", admin.getId());
        claims.put("role", "admin");
        String token = jwtUtil.generateToken(claims, admin.getUsername());
        redis.opsForValue().set("AdminJWTToken" + admin.getId() + ":", token,
                43200,
                TimeUnit.SECONDS);
        return Result.success("管理员登录成功", token);
    }

    /**
     * 登出
     *
     * @return 登出成功
     */
    @GetMapping("logout")
    public Result<String> logout() {
        adminService.logout();
        return Result.success("注销成功");
    }
}
